import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { handleGetStorage } from '@/http/auth.js'

// 创建axios实例
const request = axios.create({
  // 设置根路径
  baseURL: 'http://171.212.102.6:8399/api/v1',
  // 设置超时时间
  timeout: 5000
})
// 请求验证白名单
let whiteRequset = ["/user/login"]

// 请求拦截器
request.interceptors.request.use(
  // 请求成功
  config => {
    if (!whiteRequset.includes(config.url)) {  
      config.headers['token'] = handleGetStorage("token")
    }
    console.log(config.url)
    return config

  },
  // 请求失败
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(

  // 响应成功
  response => {
    const res = response.data

    if (res.code !== 200) {

      if (res.msg==="Token is null") {
        // 解决登录 token 不及时更新
        Message({
          message: '加载资源问题,重新刷新页面，请等待',
          type: 'info',
          duration: 6 * 1000,
          showClose:true
        })

        window.location.reload()

      }else{

        // 显示错误信息提示
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000,
          showClose:true
        })
      }


      // 
      if (res.code === 401 || res.code === 403) {
        // 提示进行重新登录
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
        //   // 将token清除
        //   store.dispatch('user/resetToken').then(() => {
        //     // 刷新页面
        //     location.reload()
        //   })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },

  // 响应失败
  error => {
    Message({
      message: error,
      type: 'error',
      duration: 5 * 1000,
      showClose:true
    })
    return Promise.reject(error)
  }
)

export default ({method,url,data}) => {
  return request({
    method,
    url,
    // 若 method为post 则用 data,否则用param
    [method.toLowerCase() === "get"? 'params' : 'data' ]:data
  })
} 
